package common

import (
	"fmt"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	_"syuee.com/iShot/model"
)
var DB *gorm.DB

func InitDB() *gorm.DB {
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database,
		charset,
	)
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		host,
		username,
		password,
		database,
		port,
	)

	if driverName == "mysql" {
		db, err := gorm.Open(mysql.Open(args), &gorm.Config{
			//SkipDefaultTransaction: true,
			QueryFields:            true,
			
		})
		if err != nil {
			panic("failed to connect database, err: " + err.Error())
		}
		defer DatabasePool(db)
		//db.AutoMigrate(&model.I_manager{})
		db.Debug()
		DB = db
		return db
	} else if driverName == "postgres" {
		db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
			QueryFields: true,
		})

		if err != nil {
			panic("failed to connect database, err: " + err.Error())
		}
		defer DatabasePool(db)
		//db.AutoMigrate(&model.I_manager{})

		DB = db
		return db
	} else {
		return nil
	}
}

func GetDB() *gorm.DB {
	return DB
}

//新版本中没有Cose 方法关闭连接， 有数据库连接池维护连接信息，也可以利用通用的数据库对象关掉连接
func DatabasePool(db *gorm.DB) {
	sqlDB, err := db.DB()

	if err != nil {
		panic(err)
	}
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)
}
